package com.shiwenping.reply.net;

import android.content.Context;
import android.util.Log;

import com.google.gson.Gson;
import com.shiwenping.reply.net.domain.BaseHttpResult;
import com.shiwenping.reply.tools.AllUtils;
import com.shiwenping.reply.tools.Path;
import com.shiwenping.reply.tools.sp.SharedPreferenceUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Protocol;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.ResponseBody;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

import static java.net.HttpURLConnection.HTTP_OK;

/**
 * @author shiwenping
 * @date 17-11-8 下午5:07
 */

public class ApiManager {
    private static Retrofit retrofit;

    private static Retrofit downLoadRetrofit;

    public static Retrofit fileRetrofit() {
        if (downLoadRetrofit == null) {
            OkHttpClient okHttpClient = new OkHttpClient.Builder().connectTimeout(10000, TimeUnit.SECONDS).build();
            downLoadRetrofit = new Retrofit.Builder()
                    .client(okHttpClient)
                    .build();
            return downLoadRetrofit;
        }
        return downLoadRetrofit;
    }

    public static Retrofit retrofit(Context mContext) {
        if (retrofit == null) {
            HttpLoggingInterceptor httpLoggingInterceptor = new HttpLoggingInterceptor(
                    message -> {
                        if (message.contains("-->") && message.contains("http")) {
                            Log.e("", "\r\n\r\n\r\n");
                            Log.e("okhttp开始请求", "------------------------------------------------------------------------------------------------------");
                        }
                        if (message.contains("<--") && message.contains("ms")) {
                            Log.e("", "\r\n\r\n\r\n");
                            Log.e("okhttp开始响应", "------------------------------------------------------------------------------------------------------");
                        }
//                    Log.e("okhttp　　　　　", "" + message);
                        try {

                            JSONObject jsonObject = new JSONObject(message);
                            AllUtils.printJson("okhttp　　　　　", jsonObject.toString(), "okhttp");
                        } catch (JSONException e) {
                            Log.e("okhttp　　　　　", "" + message);
                        }

                        if (message.contains("-->") && message.contains("END")) {
                            Log.e("okhttp结束请求", "------------------------------------------------------------------------------------------------------");
                            Log.e("", "\r\n\r\n\r\n");
                        }
                        if (message.contains("<--") && message.contains("END")) {
                            Log.e("okhttp结束响应", "------------------------------------------------------------------------------------------------------");
                            Log.e("", "\r\n\r\n\r\n");
                        }
                    }
            );
            httpLoggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
            OkHttpClient okHttpClient = new OkHttpClient.Builder()
                    .addInterceptor(chain -> {
                        Request request = chain.request()
                                .newBuilder()
                                .addHeader("registration_ticket", "f9b9461b134f5d470edff883b140867f")
                                .addHeader("auth_ticket", SharedPreferenceUtil.get(mContext, Path.TOKEN, ""))
                                .build();

                        Response response = null;
                        try {
                            Log.d("HaiChecker", request.url().toString());
                            response = chain.proceed(request);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (response == null || response.code() != HTTP_OK) {
                            Gson gson = new Gson();
                            BaseHttpResult baseHttpResult = new BaseHttpResult();
                            baseHttpResult.setSuccess(false);
                            baseHttpResult.setMsg("网络错误或服务器错误!");
                            return new Response.Builder()
                                    .code(200)
                                    .body(ResponseBody.create(
                                            MediaType.parse("application/json; charset=UTF-8")
                                            , gson.toJson(baseHttpResult)))
                                    .request(request)
                                    .protocol(Protocol.HTTP_1_0)
                                    .build();
                        }
                        return response;
                    })
                    .addInterceptor(httpLoggingInterceptor)
                    .retryOnConnectionFailure(true)
                    .connectTimeout(10000, TimeUnit.MILLISECONDS)
                    .build();
            retrofit = new Retrofit.Builder()
                    .baseUrl(SharedPreferenceUtil.get(mContext, Path.BASE_URL, "http://qk.call580.com:8080/"))
                    .client(okHttpClient)
                    .addConverterFactory(GsonConverterFactory.create())
                    .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                    .build();
            return retrofit;
        }
        return retrofit;
    }
}
